package com.komunide.zap.authentification;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;

/**
 * Ce service écoute les nouvelles connexions wifi et si une de celles-ci est
 * une zap, il va procéder à l'authentification zap. Si l'authentification est
 * réussie, il fait une notification à l'utilisateur.
 * 
 * @author martin hamel
 * 
 */
public class ZAPReceiver extends BroadcastReceiver {

	private NotificationManager mNM;
	// Unique Identification Number for the Notification.
	// We use it on Notification start, and to cancel it.
	private int NOTIFICATION = R.string.app_name;

	private Pattern ZAP_SSID_PATTERN = Pattern.compile("^ZAP.*");

	
	/**
	 * Si on a une connexion wifi dont le SSID commence par ZAP on lance l'authentification.
	 */
	@Override
	public void onReceive(Context context, Intent intent) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = connectivityManager.getActiveNetworkInfo();
		if (info != null && 
				info.getType() == ConnectivityManager.TYPE_WIFI &&
				info.getState().equals(NetworkInfo.DetailedState.CONNECTED)) {
			WifiManager wifiManager = (WifiManager) context
					.getSystemService(Context.WIFI_SERVICE);
			String name = wifiManager.getConnectionInfo().getSSID();
			Matcher matcher = ZAP_SSID_PATTERN.matcher(name);
			if (matcher.matches()) {
				// On vient de se connecter à un wifi
				doLogin();
			}
		}
	}

	
	/**
	 * Appel la page de login de zapquebec avec les bon paramètres.
	 */
	private void doLogin() {
		try {
			URL url = new URL("https://auth.zapquebec.org/login/index.php");

			// On créé les paramètres
			StringBuffer sb = new StringBuffer();
			sb.append("form_request=login&");
			sb.append("auth_source=default-network&");
			sb.append("username=martin@komunide.com&");
			sb.append("password=moliere32&");
			sb.append("login_form_submit=Ouvrir une session");

			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setRequestMethod("POST");

			connection.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			connection.setRequestProperty("Content-Length",
					"" + Integer.toString(sb.length()));

			connection.setUseCaches(false);
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.connect();

			DataOutputStream wr = new DataOutputStream(
					connection.getOutputStream());
			wr.writeBytes(sb.toString());

			InputStreamReader isr = new InputStreamReader(
					connection.getInputStream());
			BufferedReader br = new BufferedReader(isr);
			String ligne = br.readLine();
			while (ligne != null) {
				System.out.println(ligne);
				ligne = br.readLine();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
